package com.jbit.examSystem.service.impl;

import com.jbit.examSystem.dao.ExamClassDao;
import com.jbit.examSystem.dao.ExamDao;
import com.jbit.examSystem.pojo.Class;
import com.jbit.examSystem.pojo.Exam;
import com.jbit.examSystem.param.ExamSearchParam;
import com.jbit.examSystem.pojo.ExamAdd;
import com.jbit.examSystem.pojo.TestPaper;
import com.jbit.examSystem.service.ExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public class ExamServiceImpl implements ExamService {
    @Autowired
    private ExamDao examDao;
    @Autowired
    private ExamClassDao examClassDao;


    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public List<Exam> list(ExamSearchParam param) {
        List<Exam> exams = examDao.list(param);
        exams.forEach(exam -> {
            List<Class> classes = examClassDao.getClassByExamId(exam.getId());
            exam.setClasses(classes);
        });
        return exams;
    }

    @Override
    public void addExam(ExamAdd examAdd) {
        Exam exam = new Exam();
        TestPaper testPaper = new TestPaper();
        testPaper.setId(examAdd.getTestPaperId());

        exam.setTestPaper(testPaper);
        exam.setTitle(examAdd.getTitle());
        exam.setExamTime(examAdd.getExamTime());

        examDao.addExam(exam);
        Integer examId = exam.getId();

        Integer[] classIds = examAdd.getClassId();
        for (Integer classId : classIds) {
            examDao.addExamClass(classId,examId);
        }

    }

    @Override
    public List<Exam> getExamByClassId(Integer classId) {
        List<Exam> exams = examDao.getExamByClassId(classId);
        return exams;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public Exam getExamById(Integer examId) {
        Exam exam = examDao.getExamById(examId);
        return exam;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public List<Exam> getExamNameByClassId(Integer classId) {
        List<Exam> exams = examDao.getExamNameByClassId(classId);
        return exams;
    }


}
